//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using CommunityServer.Files.Components;
using CommunityServer.Components;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CommunityServer.Files.Controls
{
	public class FileThumbnail : Control
	{
		private CSContext csContext;
		private Post _post;

		#region Constructor

		public FileThumbnail(): base()
		{
			csContext = CSContext.Current;	
		}

		#endregion

		#region Properties

		public Post Post 
		{
			get 
			{
				if (_post == null) 
				{
					Object state = ViewState["Post"];
					if (state != null) 
					{
						Int32 postID = (Int32)state;
						_post = Entries.GetEntry(csContext.ApplicationKey, postID);
					}
					else if (csContext.PostID != -1)
					{
						_post = Entries.GetEntry(csContext.ApplicationKey, csContext.PostID);
					}
				}
				return _post;
			}
			set 
			{
				_post = value;
				if (_post != null) 
				{
					ViewState["Post"] = _post.PostID;
				} 
				else 
				{
					ViewState.Remove("Post");
				}
			}
		}

		public ImageAlign ImageAlign
		{
			get
			{
				object state = ViewState["ImageAlign"];
				if (state == null)
					return ImageAlign.AbsMiddle;
				else
					return (ImageAlign) state;
			}
			set
			{
				ViewState["ImageAlign"] = value;
			}
		}

		public FileThumbnailSize ThumbnailSize
		{
			get
			{
				object state = ViewState["ThumbnailSize"];
				if (state == null)
					return FileThumbnailSize.Normal;
				else
					return (FileThumbnailSize) state;
			}
			set
			{
				ViewState["ThumbnailSize"] = value;
			}
		}

		#endregion

		#region Render Method

		protected override void Render(HtmlTextWriter writer)
		{
			string imageUrl = Entry.GetPreviewImageUrl((Entry) Post, csContext, this.ThumbnailSize);

			if (!Globals.IsNullorEmpty(imageUrl))
			{
				writer.AddAttribute(HtmlTextWriterAttribute.Href, FileGalleryUrls.Instance().ViewEntry(Post.Section.ApplicationKey, Post.PostID));
				writer.RenderBeginTag(HtmlTextWriterTag.A);

				writer.AddAttribute(HtmlTextWriterAttribute.Src, imageUrl);
				writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
				writer.AddAttribute(HtmlTextWriterAttribute.Align, (this.ImageAlign == ImageAlign.NotSet ? ImageAlign.AbsMiddle : this.ImageAlign).ToString());
				writer.RenderBeginTag(HtmlTextWriterTag.Img);
				writer.RenderEndTag();
			
				writer.RenderEndTag();
			}
		}

		#endregion
	}
}
